package com.yekong.house.biz.service.impl;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.yekong.house.biz.mapper.HouseMapper;
import com.yekong.house.biz.service.AgencyService;
import com.yekong.house.biz.service.HouseService;
import com.yekong.house.common.constants.CommonConstants;
import com.yekong.house.common.constants.HouseUserType;
import com.yekong.house.common.model.*;
import com.yekong.house.common.page.PageData;
import com.yekong.house.common.page.PageParams;
import com.yekong.house.common.utils.BeanHelper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.stream.Collectors;

@Service
public class HouseServiceImpl implements HouseService {
    @Autowired
    private HouseMapper houseMapper;

    @Autowired
    private AgencyService agencyService;

    @Autowired
    private MailServiceImpl mailService;

    @Autowired
    private FileServiceImpl fileService;

    @Value("${file.prefix}")
    private String imgPrefix;

    /**
     * 1. 查询小区
     * 2. 添加图片服务器地址前缀
     * 3. 构建分页结果
     * 4. 支持展示图片、价格、标题、地址等信息
     *
     * @param query
     * @param pageParams
     */

    @Override
    public PageData<House> queryHouse(House query, PageParams pageParams) {
        List<House> houseList =  Lists.newArrayList();
        if(!Strings.isNullOrEmpty(query.getName())){
            Community community = new Community();
            community.setName(query.getName());
            List<Community> communities = houseMapper.selectCommunity(community);
            if(! communities.isEmpty()){
                query.setCommunityId(communities.get(0).getId());
            }
        }
        houseList = queryAndSetImg(query,pageParams);
        Long count = houseMapper.selectPageCount(query);
        return PageData.buildPage(houseList,count,pageParams.getPageSize(),pageParams.getPageNum());
    }


    /**
     * 1. 查找房屋
     * 2. 设置房屋相关图片的的前缀
     *
     * @param query
     * @param pageParams
     * @return
     */
    public List<House> queryAndSetImg(House query, PageParams pageParams) {
        List<House> houses =  houseMapper.selectPageHouses(query,pageParams);
        houses.forEach(house -> {
            house.setFirstImg(imgPrefix+ house.getFirstImg());
            house.setImageList(house.getImageList()
                    .stream()
                    .map(img->imgPrefix+img).collect(Collectors.toList()));
            house.setFloorPlanList(
                    house.getFloorPlanList()
                            .stream()
                            .map(pic -> imgPrefix+pic).collect(Collectors.toList()));
        });
        return houses;
    }



    @Override
    public int insert(House house) {
        return 0;
    }


    /**
     * 查找房屋
     * @param id
     * @return
     */
    @Override
    public House queryOneHouse(Long id) {
        House query = new House();
        query.setId(id);
        List<House> houses = queryAndSetImg(query,PageParams.build(1,1));
        if(!houses.isEmpty()){
            return houses.get(0);
        }
        return null;
    }

    @Override
    public void addUserMsg(UserMsg userMsg) {
        BeanHelper.onInsert(userMsg);
        houseMapper.insertUserMsg(userMsg);
        User agent = agencyService.getAgentDetail(userMsg.getAgentId());
        // 把用户的留言信息通过邮件发送给经纪人
        mailService.sendEmail("来自用户"+userMsg.getEmail()+"的留言:",userMsg.getMsg(),agent.getEmail());
    }

    @Override
    public HouseUser getHouseUser(Long houseId) {
        HouseUser houseUser =  houseMapper.selectSaleHouseUser(houseId);
        return houseUser;
    }

    /**
     * 获取所有小区
     *
     * @return
     */

    @Override
    public List<Community> getAllCommunitys() {

        Community community = new Community();
        return houseMapper.selectCommunity(community);
    }


    /**
     *  1. 添加房产图片
     *  2. 添加户型图片
     *  3. 插入房产信息
     *  4. 绑定用户到房产的关系
     * @param house
     * @param user
     */
    @Override
    public void addHouse(House house, User user) {
        // 设置房屋图片
        if(CollectionUtils.isNotEmpty(house.getHouseFiles())){
            String images = Joiner.on(",").join(fileService.getImgPath(house.getHouseFiles()));
            house.setImages(images);
        }
        // 设置户型图
        if(CollectionUtils.isNotEmpty(house.getFloorPlanFiles())){
            String images = Joiner.on(",").join(fileService.getImgPath(house.getFloorPlanFiles()));
            house.setFloorPlan(images);
        }
        // 设置创建时间
        BeanHelper.onInsert(house);
        houseMapper.insert(house);
        bindUser2House(house.getId(),user.getId(),false);

    }

    /**
     * 更新评分
     *
     * @param id
     * @param rating
     */
    @Override
    public void updateRating(Long id, Double rating) {
        House house = queryOneHouse(id);
        Double oldRating = house.getRating();
        Double newRating = oldRating.equals(0D)?rating:Math.min((oldRating+rating)/2,5);
        House updateHouse = new House();
        updateHouse.setId(id);
        updateHouse.setRating(newRating);
        BeanHelper.onUpdate(updateHouse);
        houseMapper.updateHouse(updateHouse);
    }

    /**
     * 1. 添加收藏
     *
     * @param houseId
     * @param userId
     * @param isCollect
     */
    public void bindUser2House(Long houseId, Long userId, boolean isCollect) {
        HouseUser existHouseUser = houseMapper.selectHouseUser(userId,houseId,isCollect?HouseUserType.BOOKMAKR.value:HouseUserType.SALE.value);
        if (existHouseUser!=null){
            return ;
        }
        HouseUser houseUser =new HouseUser();
        houseUser.setHouseId(houseId);
        houseUser.setUserId(userId);
        houseUser.setType(isCollect?HouseUserType.BOOKMAKR.value:HouseUserType.SALE.value);
        //设置默认值
        BeanHelper.setDefaultProp(houseUser,HouseUser.class);
        //设置创建时间
        BeanHelper.onInsert(houseUser);
        houseMapper.insertHouseUser(houseUser);
    }


    // 删除收藏
    @Override
    public void unbindUser2House(Long id, Long id2, HouseUserType bookmark) {
        houseMapper.deleteHouseUser(id,id2,bookmark.value);
    }





}
